<script setup lang='ts'>
import Motion from "../utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "../utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
const env = import.meta.env;
defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const userStore = useUserStoreHook()
const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title } = useNav();

const ruleForm = reactive({
  username: env.DEV ? "test255" : '',
  password: env.DEV ? "123456" : ''
});

const onLogin = async (formEl?: FormInstance) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      userStore
        .loginByUsername({ username: ruleForm.username, pwd: ruleForm.password })
        .then(res => {
          // 获取后端路由
          return initRouter().then(() => {
            router.push(getTopMenu(true).path)
              .then(() => {
                message("登录成功", { type: "success" });
              });
          });
        }, e => {
          console.log(e);

          message(`登录失败:${e ? e.message : ''}`, { type: "error" });
        })
        .finally(() => (loading.value = false));
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <el-form v-if="!userStore.currentPage" ref="ruleFormRef" :model="ruleForm" :rules="loginRules" size="large">
    <Motion :delay="100">
      <el-form-item :rules="[
        {
          required: true,
          message: '请输入账号',
          trigger: 'blur'
        }
      ]" prop="username">
        <el-input v-model="ruleForm.username" clearable placeholder="账号" :prefix-icon="useRenderIcon(User)" />
      </el-form-item>
    </Motion>

    <Motion :delay="150">
      <el-form-item prop="password">
        <el-input v-model="ruleForm.password" clearable show-password placeholder="密码"
          :prefix-icon="useRenderIcon(Lock)" />
      </el-form-item>
    </Motion>

    <Motion :delay="250">
      <el-button class="w-full mt-4" size="default" type="primary" :loading="loading" @click="onLogin(ruleFormRef)">
        登录
      </el-button>
    </Motion>
  </el-form>
</template>

<style lang='scss' scoped></style>
